package com.meichis.mcsappframework.utils;

import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipTool {
	/**
	 * GZIP 
	 * GZIP压缩
	 * @param str
	 * @return
	 */
	public static String encryptGZIP(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}

		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			GZIPOutputStream gzip = new GZIPOutputStream(baos);
			gzip.write(str.getBytes("UTF-8"));

			gzip.close();

			byte[] encode = baos.toByteArray();

			baos.flush();
			baos.close();

			return Base64.encodeToString(encode, Base64.DEFAULT);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * GZIP
	 * 解压
	 * @param str
	 * @return
	 */
	public static String decryptGZIP(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}

		try {

			byte[] decode;


			ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(str, Base64.DEFAULT));
			GZIPInputStream gzip = new GZIPInputStream(bais);
			byte[] buf = new byte[1024];
			int len = 0;

			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			while ((len = gzip.read(buf, 0, 1024)) != -1) {
				baos.write(buf, 0, len);
			}
			gzip.close();
			baos.flush();

			decode = baos.toByteArray();
			baos.close();
			return new String(decode, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}
